package obs.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import obs.form.LoginForm;
import obs.service.LoginService;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class LoginAction extends Action {

    @Autowired
    private LoginService loginService;

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        LoginForm loginForm = (LoginForm) form;
        boolean ok = loginService.login(loginForm.getUsername(), loginForm.getPassword());
        String msg = "";
        if (ok) {
            request.getSession().setAttribute("USER_INFO", loginForm);
            return mapping.findForward("success");
        } else {
            msg = "login failed.";
            ActionMessage message = new ActionMessage(msg, false);
            ActionMessages messages = new ActionMessages();
            messages.add("msg", message);
            saveMessages(request, messages);
        }
        return mapping.findForward("fail");
    }

}
